const { readFile, writeFile,eraseFile } = require("../common/common.js");
const {
  DATA_PATH,
  REPORT_PATH,
} = require("../config/config.default.js");
const officegen = require("officegen");
const err = require("../constant/err.type.js");
const fs = require("fs");
const path = require("path");
const Router = require("koa-router");
const router = new Router();

const {saveLink,createLink,eraseLink,getLinks,createWork,eraseWork} = require("../controller/links.controller.js");
const {saveNode,createNode,eraseNode,getNodes,batchAddNodes} = require("../controller/nodes.controller.js");
const {saveOptical,createOptical,batchAddOptical,eraseOptical,getOpticals} = require("../controller/opticals.controller.js");
const {getConfig,saveConfig} = require("../controller/configs.controller.js");
const {getGaojing,updateJson} = require("../common/common.js")
const {getOptical} = require("../services/opticals.service.js")
const {saveLinks,getLinkByName} = require("../services/links.service.js")
/* //读取router下面的所有文件
router.get("/", async (ctx, netx) => {
  await ctx.render("index.html");
});
router.post("/getList", async (ctx, netx) => {
  var res = await readFile(LIST_PATH);
  ctx.body = JSON.stringify({ code: 0, msg: "ok", data: res });
});
router.post("/setData", async (ctx, next) => {
  try {
    var { info, param, md } = ctx.request.body;
    console.log("info:", info);
    console.log("param:", param);
    //md为1时，为解除故障
    console.log("md:", md);
    if (md > 0) {
      param = {};
    }
    var res = await writeFile(DATA_PATH, JSON.stringify(info));
    var rs = await writeFile(
      path.join(__dirname, "../", "data/data.json"),
      JSON.stringify(param)
    );
    if (!res) {
      ctx.body = { code: -1, msg: "写入json数据失败", data: "" };
      return;
    }
    if (!rs) {
      ctx.body = { code: -1, msg: "写入中转数据失败", data: "" };
      return;
    }
    //以下代码为读取原始数据，并把修改保存在原始数据中
    // var list = await readFile(LIST_PATH);
    // var id = 0;
    // var arr = [];
    // for (var i = 0; i < list.length; i++) {
    //   if (param.id == list[i]["id"]) {
    //     id = i;
    //     arr = list[i]["subsection"];
    //     break;
    //   }
    // }
    // for (var i = 0; i < list[id]["subsection"].length; i++) {
    //   if (param.sub == list[id]["subsection"][i]["id"]) {
    //     let cl;
    //     if (md > 0) {
    //       cl = "green";
    //     } else {
    //       cl = "red";
    //     }
    //     let item = {
    //       id: list[id]["subsection"][i]["id"],
    //       name: list[id]["subsection"][i]["name"],
    //       color: cl,
    //       type: param.type,
    //       distance: list[id]["subsection"][i]["distance"],
    //       service: list[id]["subsection"][i]["service"],
    //     };
    //     console.log("item:",item);
    //     list[id]["subsection"].splice(i, 1, item);
    //     break;
    //   }
    // }
    // let ws = await writeFile(LIST_PATH, JSON.stringify(list));
    ctx.body = { code: 0, msg: "ok", data: "" };
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: -1,
      msg: error,
      data: { info, param },
    };
  }
});
router.post("/getParam", async (ctx, next) => {
  try {
    var res = await readFile(path.join(__dirname, "../", "data/data.json"));
    ctx.body = { code: 0, msg: "ok", data: res };
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: -1,
      msg: error,
      data: "",
    };
  }
});
router.post("/makeReport", async (ctx, next) => {
  try {
    console.log("param");
    var { param } = ctx.request.body;
    console.log(param);
    if (Object.keys(param).length > 0) {
      console.log("world");
      let docx = officegen("docx");
      docx.on("finalize", (written) => {
        console.log("finish to create a word document");
      });
      docx.on("error", (err) => {
        console.log(err);
      });
      let pObj = docx.createP({ align: "center" }); //创建行并设置水平居中
      pObj.addText("光缆故障报告", { font_size: 22, font_face: "黑体" });
      pObj.addLineBreak(); //换行
      pObj = docx.createP(); //创建行
      pObj.addText(`光缆名称：${param.line}`, {
        font_face: "宋体",
        font_size: 16,
      });
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addText(`涉及业务名称：${param.service}`, {
        font_face: "宋体",
        font_size: 16,
      });
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addText(`故障类型：${param.type}`, {
        font_face: "宋体",
        font_size: 16,
      });
      pObj = docx.createP();
      var t = new Date();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addText(`故障时间：${param.time}`, {
        font_face: "宋体",
        font_size: 16,
      });
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addText(`故障点距起点：${param.distance}米`, {
        font_face: "宋体",
        font_size: 16,
      });
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      var position = "";
      if (param.code == 1) {
        position = `位于${param.start}和1#故障定位器之间，距${param.start}${param.position}米`;
      } else if (param.code == 2) {
        position = `位于1#故障定位器和2#故障定位器之间，距1#故障定位器${param.position}米`;
      } else if (param.code == 3) {
        position = `位于2#故障定位器和${param.end}之间，距2#故障定位器${param.position}米`;
      }
      pObj.addText(`故障点地理位置：${position}`, {
        font_face: "宋体",
        font_size: 16,
      });
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addText(`联系人：${param.concate}`, {
        font_face: "宋体",
        font_size: 16,
      });
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addText(`光传输面板：两张图`, { font_face: "宋体", font_size: 16 });
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addImage(path.join(__dirname, "../", "public/img/m1.jpg"));
      pObj.addImage(path.join(__dirname, "../", "public/img/m2.jpg"));
      pObj = docx.createP();
      pObj.addText("\t", {
        font_face: "宋体",
        font_size: 16,
      });
      pObj.addText(
        `故障解除时间${t.getFullYear()}.${
          t.getMonth() + 1
        }.${t.getDate()}    ${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}`,
        { font_face: "宋体", font_size: 16 }
      );
      pObj.addLineBreak();
      let filename =
        REPORT_PATH +
        `${t.getFullYear()}${
          t.getMonth() + 1
        }${t.getDate()}${t.getHours()}${t.getMinutes()}${t.getSeconds()}.docx`;
      let out = fs.createWriteStream(filename);
      out.on("error", (err) => {
        console.log(err);
      });
      docx.generate(out);
      ctx.body = { code: 0, msg: "ok", data: "" };
      return;
    } else {
      ctx.body = { code: -1, msg: "写入报告失败", data: "" };
    }
  } catch (error) {
    console.log(error);
    ctx.body = { code: -1, msg: error, data: "" };
  }
}); */
router.get("/admin",async (ctx,next) => {
  await ctx.render("admin.html")
})
router.get("/llgl",async (ctx,next) => {
  await ctx.render("llgl.html");
})
router.get("/zcgl",async (ctx,next) => {
  console.log(111);
  await ctx.render("occ.html");
})
router.get("/btgdj",async(ctx,next) => {
  await ctx.render("btgdj.html")
})
router.get("/gllist",async (ctx,next) =>{
  await ctx.render("gllist.html")
})
router.get("/line",async (ctx,next) => {
  await ctx.render("line.html");
})
router.get("/mnyx",async (ctx,next) => {
  await ctx.render("mnyx.html")
})
router.get("/gzgj",async (ctx,next) => {
  await ctx.render("gzgj.html")
})


router.post("/getLinks",getLinks);
router.post("/createLink",createLink);
router.post("/modifyLink",saveLink);
router.post("/eraseLink",eraseLink);
router.post("/createWork",createWork);
router.post("/eraseWork",eraseWork);
router.post("/createNode",createNode);
router.post("/importNodes",batchAddNodes);
router.post("/getNodes",getNodes);
router.post("/modifyNode",saveNode);
router.post("/eraseNode",eraseNode);
router.post("/getOpticals",getOpticals);
router.post("/modifyOptical",saveOptical);
router.post("/importOpticals",batchAddOptical);
router.post("/eraseOptical",eraseOptical);
router.post("/createOptical",createOptical);
router.post("/getConfig",getConfig);
router.post("/saveConfig",saveConfig)


/* 
JSON操作
*/
//导入节点时，创建Js_node.json
router.post("/jsonImportOpticals",async (ctx,next) => {
  try {
    var res;
    var {linkId,arr} = ctx.request.body;
    console.log("linkId=>",linkId);
    if(linkId <= 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"获取JSON文件名编号失败",data:""}),ctx);
      return;
    }
    var jsonName = `${DATA_PATH}Js_Node${linkId}.json`;
    var data = [];
    if(arr instanceof Array){
      var list = []
      if(arr.length > 0){
        for(var i=0;i<arr.length;i++){
          let obj = {ID:`L${linkId}N${i}`,class:"Node",Name:`BP_Node_L${linkId}N${i}`,Mesh:arr[i]['nodeType'],X:3836187.737 * (0 + arr[i]['longitude'] - 109.88598) / 0.86915612,Y:-7091297.591 * (0 + arr[i]['latitude'] - 40.65176) / 1.20283173,Z:"4000",Build:"1",Click:"0",R:arr[i]['R'],G:arr[i]['G'],B:arr[i]['B']};
          list.push(obj);
        }
      }
      data = {sites:list,status:{Color:""}};
    }else{
      data = {sites:[],status:{Color:""}};
    }
    var res = await writeFile(jsonName,JSON.stringify(data));
    if(res){
      updateJson(`${DATA_PATH}Js_UpData.json`);
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入JSON成功",data:""}),ctx);
      return;
    }else{
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入JSON失败",data:""}),ctx);
      return;
    }
  } catch (error) {
    ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
//删除节点时，处理Js_Node.json中的数据
router.post("/jsonEraseOpticals",async (ctx,next) => {
  try {
    var res;
    var {linkId} = ctx.request.body;
    if(linkId <= 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"获取JSON文件名编号失败",data:""}),ctx);
      return;
    }
    var jsonName = `${DATA_PATH}Js_Node${linkId}.json`;
    res = await eraseFile(jsonName);
    if(res){
      updateJson(`${DATA_PATH}Js_UpData.json`);
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"删除JSON成功",data:""}),ctx);
      return;
    }else{
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"删除JSON失败",data:""}),ctx);
      return;
    }
  } catch (error) {
    ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
//删除线路
router.post("/jsonEraseLink",async (ctx,next) => {
  try {
    var res;
    var {linkId} = ctx.request.body;
    if(linkId <= 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"获取JSON文件名编号失败",data:""}),ctx);
      return;
    }
    var jsonName = `${DATA_PATH}Js_Node${linkId}.json`;
    res = await eraseFile(jsonName);
    if(res){
      updateJson(`${DATA_PATH}Js_UpData.json`);
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"删除JSON成功",data:""}),ctx);
      return;
    }else{
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"删除JSON失败",data:""}),ctx);
      return;
    }
  } catch (error) {
    ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
//设置故障告警
router.post("/setHitch",async (ctx,next) => {
  try {
    var res;
    var {linkId,linkName,status,statusValue,lineName,times,cancat,works} = ctx.request.body;
    if(!linkName){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路名称错误 ",data:""}),ctx);
      return;
    }
    let ss = await saveLinks({linkId,status,statusValue});
    if(!ss){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"保存线路信息失败",data:""}),ctx);
      return;
    }
    var rs = await getOptical({linkName});
    if(!rs || !(rs instanceof Array) || rs.length == 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"获取坐标信息错误",data:""}),ctx);
      return;
    }
    let list = rs;
    //计算告警信息
    res = getGaojing(list,statusValue);
    let url = ctx.request.host;
    if(res.code == 0){
      let point = {ID:`GZGJ1`,Class:"GZ",Name:`BP_POI_GZGJ1`,Show_Name:linkName,Mesh:"SM_GZGJ",X:res.data.x,Y:res.data.y,Z:"8000",URL:`http://${url}/gzgj?linkId=${linkId}`,Build:"1",Visible:"1",Click:"1",Init:"0",R:"1",G:"0",B:"0",Color:""}
      var fileName = `${DATA_PATH}Js_GZGJ.json`;
      var json = [];
      json.push(point);
      var is = await writeFile(fileName,JSON.stringify({sites:json}));
      if(!is){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入Js_GZGJ.json失败",data:""}),ctx);
        return;
      }
      var poiName = `${DATA_PATH}Js_POI.json`;
      var poi;
      var poiObj = await readFile(poiName,2);
      if(Object.keys(poiObj).length == 0 || !poiObj['sites'] || !(poiObj['sites'] instanceof Array) || poiObj['sites'].length < 2){
        poi = [{},{ID:"GDJ0",Class:"Centre",Name:"BP_POI_GDJ0",Mesh:"SM_GDJ",X:"0",Y:"0",Z:"0",URL:"btgdj.html",Build:"1",Visible:"1",Click:"0",Init:"0",Color:"Green",R:"",G:"",B:""}];
      }else{
        poi = poiObj['sites'];
      }
      poi.splice(0,1,point);
      var ps = await writeFile(poiName,JSON.stringify({sites:poi}));
      if(ps){
        let obj = {type:res.data.type,origin:res.data.origin,finishing:res.data.finishing,finishingId:res.data.finishingId,distance:res.data.distance,X:res.data.x,Y:res.data.y,linkId,linkName,lineName,times,status,statusValue,cancat,works};
        let rsFile = `${DATA_PATH}gaojing.json`;
        writeFile(rsFile,JSON.stringify(obj));
        setTimeout(async () => {
          json[0]['Click'] = "0";
          /* json[0]['R'] = "0";
          json[0]['G'] = "0";
          json[0]['B'] = "0"; */
          let tmp = await writeFile(fileName,JSON.stringify({sites:json}));
          poi[0]['Click'] = "0";
          /* poi[0]['R'] = "0";
          poi[0]['G'] = "0";
          poi[0]['B'] = "0"; */
          await writeFile(poiName,JSON.stringify({sites:poi}));
          updateJson(`${DATA_PATH}Js_UpData.json`);
        },500);//此处的数值代表点击模拟演习按钮时，把Js_POI.json中的Click变成1，过段时间后变成0，数值代表过多长时间后变成0，单位是毫秒，同时，会把Js_GZGJ.json中的Click也变成1，过段时间后变成了
        ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入JSON成功",data:""}),ctx);
        return;
      }else{
        ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POl失败",data:""}),ctx);
        return;
      }
    }else{
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:res.msg,data:res.data}),ctx);
      return;
    }
  } catch (error) {
    console.log(error);
    ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
});
router.post("/addLink",async (ctx,next) => {
  try {
    
  } catch (error) {
    ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})

//获取GZGJ.json中的信息
router.post("/getGaojing",async (ctx,next) => {
  try {
    var res;
    let fileName = `${DATA_PATH}gaojing.json`;
    var json = await readFile(fileName,2);
    if(!json || !(json instanceof Object) || Object.keys(json).length == 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"读取信息失败",data:""}),ctx);
      return;
    }
    ctx.app.emit("error",err.setDefaultValue({code:0,msg:"ok",data:json}),ctx);
    return;
  } catch (error) {
    ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
//故障定位 
router.post("/dingwei",async (ctx,next) => {
  try {
    var res;
    let gaojinFile = `${DATA_PATH}Js_GZGJ.json`;
    let poiFile = `${DATA_PATH}Js_POI.json`;
    let gaojingData = await readFile(gaojinFile,2)
    let poiData = await readFile(poiFile,2);
    gaojingData['sites'][0]['Click'] = "1";
    await writeFile(gaojinFile,JSON.stringify(gaojingData))
    poiData['sites'][0]['Click'] = "1";
    await writeFile(poiFile,JSON.stringify(poiData));
    setTimeout(async () => {
      gaojingData['sites'][0]['Click'] = "0";
      await writeFile(gaojinFile,JSON.stringify(gaojingData))
      poiData['sites'][0]['Click'] = "0";
      await writeFile(poiFile,JSON.stringify(poiData));
    },500)//此处的数值，代表，点击故障定位按钮时，click变成1，过段时间变成0，其中的50代表过多长时间后变回0，单位是毫秒
    ctx.app.emit("error",err.setDefaultValue({code:0,msg:"OK",data:""}),ctx);
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
//解除故障，Js_POI.josn和Js_GZGJ.json修改click的值
router.post("/jiechu",async (ctx,next) => {
  try {
    var {linkName} = ctx.request.body;
    var res;
    /* let ss = await saveLinks({linkId,status,statusValue});
    if(!ss){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"保存线路信息失败",data:""}),ctx);
      return;
    } */
    let gaojinFile = `${DATA_PATH}Js_GZGJ.json`;
    let poiFile = `${DATA_PATH}Js_POI.json`;
    let gaojingData = await readFile(gaojinFile,2)
    let poiData = await readFile(poiFile,2);
    gaojingData['sites'][0]['Init'] = "1";
    gaojingData['sites'][0]['X'] = "0";
    gaojingData['sites'][0]['Y'] = "0";
    gaojingData['sites'][0]['Z'] = "8000000";
    await writeFile(gaojinFile,JSON.stringify(gaojingData))
    poiData['sites'][0]['Init'] = "1";
    poiData['sites'][0]['X'] = "0";
    poiData['sites'][0]['Y'] = "0";
    poiData['sites'][0]['Z'] = "8000000";
    await writeFile(poiFile,JSON.stringify(poiData));
    setTimeout(async () => {
      gaojingData['sites'][0]['Init'] = "0";
      await writeFile(gaojinFile,JSON.stringify(gaojingData))
      poiData['sites'][0]['Init'] = "0";
      await writeFile(poiFile,JSON.stringify(poiData));
    },500)//解除故障时0.5秒后init变成0
    var link = await getLinkByName(linkName);
    if(link instanceof Object){
      let ss = await saveLinks({linkId:link.linkId,status:"正常",statusValue:""});
      if(!ss){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"保存线路信息失败",data:""}),ctx);
        return;
      }
    }else{
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"保存线路信息失败",data:""}),ctx);
        return;
    }
    ctx.app.emit("error",err.setDefaultValue({code:0,msg:"OK",data:""}),ctx);
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
//在Js_POI.json创建line
router.post("/jsonCreateLine",async (ctx,next) => {
  try {
    var res;
    var {linkId,linkName,arr} = ctx.request.body;
    if(!linkId){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路ID错误",data:""}),ctx);
      return;
    }
    if(!linkName){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路名称错误",data:""}),ctx);
      return;
    }
    if(!(arr instanceof Array) || arr.length < 2){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"没有可添加的节点",data:""}),ctx);
      return;
    }
    var len = arr.length;
    let url = ctx.request.host;
    let num = len % 2 == 0 ? len / 2 - 1 : Math.floor(len / 2) - 1;
    let x = 3836187.737 * (0 + arr[num]['longitude'] - 109.88598) / 0.86915612;
    let y = -7091297.591 * (0 + arr[num]['latitude'] - 40.65176) / 1.20283173;
    let R = arr[num]['R'];
    let G = arr[num]['G'];
    let B = arr[num]['B'];
    let obj = {ID:`Line${linkId}`,Class:"Line",Name:`BP_POI_Line${linkId}`,Show_Name:linkName,Mesh:"SM_Line",X:x.toString(),Y:y.toString(),Z:"5000",URL:`http://${url}/line?linkId=${linkId}`,Build:"1",Visible:"1",Click:"0",Init:"0",Color:"Green",R:R,G:G,B:B}
    let poiFile = `${DATA_PATH}Js_POI.json`;
    let poiData = await readFile(poiFile,2);
    if(!poiData || !(poiData instanceof Object) || Object.keys(poiData).length == 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"读取Js_POI.json失败",data:""}),ctx);
      return;
    }
    let list = poiData['sites'];
    if(!(list instanceof Array) || list.length < 2){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"Js_POI.json中数据不完整",data:arr}),ctx);
      return;
    }else{
      if(list.length == 2){
        list.push(obj);
      }else{
        var add = true;
        for(var i=2;i<list.length;i++){
          if(list[i]['ID'] == `Line${linkId}`){
            list.splice(i,1,obj);
            add = false;
          }
        }
        if(add){
          list.push(obj);
        }
      }
      let ws = await writeFile(poiFile,JSON.stringify({sites:list}));
      updateJson(`${DATA_PATH}Js_UpData.json`);
      if(!ws){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入Js_POI.json失败",data:""}),ctx);
        return;
      }else{
        ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POI.json成功",data:""}),ctx);
        return;
      }
    }
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
//删除坐标信息时，修改POI
router.post("/lineEraseNode",async (ctx,next) => {
  try {
    var {linkId} = ctx.request.body;
    if(!linkId){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路ID错误",data:""}),ctx);
      return;
    }
    let poiFile = `${DATA_PATH}Js_POI.json`;
    let poiData = await readFile(poiFile,2);
    if(!poiData || !(poiData instanceof Object) || Object.keys(poiData).length == 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"读取Js_POI.json失败",data:""}),ctx);
      return;
    }
    let list = poiData['sites'];
    if(!(list instanceof Array) || list.length < 3){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"Js_POI.json中数据不完整",data:arr}),ctx);
      return;
    }else{
      for(var i=2;i<list.length;i++){
        if(list[i]['ID'] == `Line${linkId}`){
          list[i]['Build'] = "0";
        }
      }
      let ws = await writeFile(poiFile,JSON.stringify({sites:list}));
      updateJson(`${DATA_PATH}Js_UpData.json`);
      if(!ws){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入Js_POI.json失败",data:""}),ctx);
        return;
      }else{
        ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POI.json成功",data:""}),ctx);
        return;
      }
    }
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})

//删除线时，修改POI
router.post("/lineEraseLink",async (ctx,next) => {
  try {
    var {linkId} = ctx.request.body;
    if(!linkId){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路ID错误",data:""}),ctx);
      return;
    }
    let poiFile = `${DATA_PATH}Js_POI.json`;
    let poiData = await readFile(poiFile,2);
    if(!poiData || !(poiData instanceof Object) || Object.keys(poiData).length == 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"读取Js_POI.json失败",data:""}),ctx);
      return;
    }
    let list = poiData['sites'];
    if(!(list instanceof Array) || list.length < 3){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"Js_POI.json中数据不完整",data:arr}),ctx);
      return;
    }else{
      for(var i=2;i<list.length;i++){
        if(list[i]['ID'] == `Line${linkId}`){
          list[i]['Init'] = "1";
          list[i]['X'] = "0";
          list[i]['Y'] = "0";
          list[i]['Z'] = "8000000";
        }
      }
      let ws = await writeFile(poiFile,JSON.stringify({sites:list}));
      updateJson(`${DATA_PATH}Js_UpData.json`);
      if(!ws){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入Js_POI.json失败",data:""}),ctx);
        return;
      }else{
        ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POI.json成功",data:""}),ctx);
        return;
      }
    }
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})

//点击线路修改visible和click属性
router.post("/hitLine",async (ctx,next) => {
  try {
    var res;
    var {linkId} = ctx.request.body;
    if(linkId <= 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路ID错误",data:""}),ctx);
      return;
    }
    let poiFile = `${DATA_PATH}Js_POI.json`;
    let poiData = await readFile(poiFile,2);
    if(!poiData || !(poiData instanceof Object) || Object.keys(poiData).length == 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"读取Js_POI.json失败",data:""}),ctx);
      return;
    }
    let list = poiData['sites'];
    if(!(list instanceof Array) || list.length < 3){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"Js_POI.json中数据不完整",data:arr}),ctx);
      return;
    }else{
      for(var i=2;i<list.length;i++){
        if(list[i]['ID'] == `Line${linkId}`){
          list[i]['Click'] = "1";
        }else{
          list[i]['Visible'] = "0";
        }
      }
      let ws = await writeFile(poiFile,JSON.stringify({sites:list}));
      if(!ws){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入Js_POI.json失败",data:""}),ctx);
        return;
      }else{
        setTimeout(async () => {
          for(var i=2;i<list.length;i++){
            if(list[i]['ID'] == `Line${linkId}`){
              list[i]['Click'] = "0";
              break;
            }
          }
          await writeFile(poiFile,JSON.stringify({sites:list}));
        },500)//此处的数值，代表，在gllist页面中，点击某条线路时，click变成1，过段时间变成0，其中的50代表过多长时间后变回0，单位是毫秒
        ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POI.json成功",data:""}),ctx);
        return;
      }
    }
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
router.post("/updateJsonFile",async (ctx,next) => {
  try {
    var res = await updateJson(`${DATA_PATH}Js_UpData.json`);
    ctx.app.emit("error",err.setDefaultValue(res),ctx);
    return;
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
router.post("/setShowName",async (ctx,next) => {
  try {
    var res ;
    var {linkId,linkName} = ctx.request.body;
    if(!linkId || linkId <= 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"linkId错误",data:""}),ctx);
      return;
    }
    if(!linkName || linkName <= 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路名称错误",data:""}),ctx);
      return;
    }
    let poiFile = `${DATA_PATH}Js_POI.json`;
    let poiData = await readFile(poiFile,2);
    if(!poiData || !(poiData instanceof Object) || Object.keys(poiData).length == 0){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"读取Js_POI.json失败",data:""}),ctx);
      return;
    }
    let list = poiData['sites'];
    if(!(list instanceof Array) || list.length < 3){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"Js_POI.json中数据不完整",data:arr}),ctx);
      return;
    }else{
      let update = false;
      for(var i=2;i<list.length;i++){
        if(list[i]['ID'] == `Line${linkId}`){
          list[i]['Show_Name'] = linkName;
          update = true;
          break;
        }
      }
      if(update){
        let ws = await writeFile(poiFile,JSON.stringify({sites:list}));
        if(!ws){
          ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入Js_POI.json失败",data:""}),ctx);
          return;
        }else{
          ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POI.json成功",data:""}),ctx);
          return;
        }
      }
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POI.json成功",data:""}),ctx);
      return;
    }
  } catch (error) {
    console.log(error);
    tx.app.emit("error",err.setDefaultValue({code:-1,msg:"未知错误" + error,data:""}),ctx);
    return;
  }
})
router.post("/api/gzgj",async (ctx,next) => {
  try {
    var obj = ctx.request.body;
    console.log("obj=>",obj);
    if(!obj.linkName ){
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"参数错误",data:obj}),ctx);
      return;
    }
    if(!obj.alarmType || obj.alarmType < 0){
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"告警类型编码错误",data:obj.alarmType}),ctx);
      return;
    }
    if(!obj.alarmDetails || obj.alarmDetails <= 0){
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"告警详细内容错误",data:obj.alarmDetails}),ctx);
      return;
    }
    /* if(obj.alarmDescribe.衰减值 >= 0){
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"衰减值错误",data:obj.alarmDetails}),ctx);
      return;
    }
    if(!obj.alarmDescribe.告警描述){
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"告警描述错误",data:obj.alarmDetails}),ctx);
      return;
    } */
    if(!obj.alarmDescribe.position){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"告警长度错误",data:obj.alarmDetails}),ctx);
      return;
    }
    if(!obj.alarmDescribe.latitude){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"纬度错误",data:obj.alarmDetails}),ctx);
      return;
    }
    if(!obj.alarmDescribe.longitude){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"经度错误",data:obj.alarmDetails}),ctx);
      return;
    }
    let lk = await getLinkByName(obj.linkName);
    if(!lk){
      ctx.app.emit("error",err.setDefaultValue({code:-1,msg:'查找链路失败',data:""}),ctx)
    }
    let data = {
      linkName:lk.linkName,
      linkId:lk.linkId,
      Longitude:obj.alarmDescribe.longitude,
      Latitude:obj.alarmDescribe.latitude,
      lineName:lk.lineName,
      times:lk.times,
      cancat:lk.cancat,
      works:lk.works
    }
    if(obj.alarmType == 50 || obj.alarmType == 6){
      data.status = "中断";
    }else if(obj.alarmType == 51 || obj.alarmType == 53 || obj.alarmType == 56){
      data.status = "正常"
    }else if(obj.alarmType == 52){
      data.status = "衰减"
    }else{
      data.status = "中断"
    }
    if(obj.alarmDescribe.Position){
      data.statusValue = obj.alarmDescribe.Position;
    }
    var link = await getLinkByName(data.linkName);
    if(data.status == "正常"){
      //解除报警
      let gaojinFile = `${DATA_PATH}Js_GZGJ.json`;
      let poiFile = `${DATA_PATH}Js_POI.json`;
      let gaojingData = await readFile(gaojinFile,2)
      let poiData = await readFile(poiFile,2);
      gaojingData['sites'][0]['Init'] = "1";
      gaojingData['sites'][0]['X'] = "0";
      gaojingData['sites'][0]['Y'] = "0";
      gaojingData['sites'][0]['Z'] = "8000000";
      await writeFile(gaojinFile,JSON.stringify(gaojingData))
      poiData['sites'][0]['Init'] = "1";
      poiData['sites'][0]['X'] = "0";
      poiData['sites'][0]['Y'] = "0";
      poiData['sites'][0]['Z'] = "8000000";
      await writeFile(poiFile,JSON.stringify(poiData));
      setTimeout(async () => {
        gaojingData['sites'][0]['Init'] = "0";
        await writeFile(gaojinFile,JSON.stringify(gaojingData))
        poiData['sites'][0]['Init'] = "0";
        await writeFile(poiFile,JSON.stringify(poiData));
      },500)//解除故障时0.5秒后init变成0
      
      if(link instanceof Object){
        let ss = await saveLinks({linkId:link.linkId,status:"正常",statusValue:""});
        if(!ss){
          ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"保存线路信息失败",data:""}),ctx);
          return;
        }
      }else{
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"保存线路信息失败",data:""}),ctx);
          return;
      }
      ctx.app.emit("error",err.setDefaultValue({code:0,msg:"OK",data:""}),ctx);
    }else{
      //设置报警
      var res;
      if(!data.linkName){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"线路名称错误 ",data:""}),ctx);
        return;
      }
      let pd = {linkId:link.linkId,status:data.status,statusValue:data.statusValue}
      let ss = await saveLinks(pd);
      if(!ss){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"保存线路信息失败",data:""}),ctx);
        return;
      }
      var rs = await getOptical({linkName:data.linkName});
      if(!rs || !(rs instanceof Array) || rs.length == 0){
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"获取坐标信息错误",data:""}),ctx);
        return;
      }
      let list = rs;
      //计算告警信息
      res = getGaojing(list,data.statusValue);
      let url = ctx.request.host;
      if(res.code == 0){
        let point = {ID:`GZGJ1`,Class:"GZ",Name:`BP_POI_GZGJ1`,Show_Name:link.linkName,Mesh:"SM_GZGJ",X:res.data.x,Y:res.data.y,Z:"8000",URL:`http://${url}/gzgj?linkId=${link.linkId}`,Build:"1",Visible:"1",Click:"1",Init:"0",R:"1",G:"0",B:"0",Color:""}
        var fileName = `${DATA_PATH}Js_GZGJ.json`;
        var json = [];
        json.push(point);
        var is = await writeFile(fileName,JSON.stringify({sites:json}));
        if(!is){
          ctx.app.emit("error",err.setDefaultValue({code:-1,msg:"写入Js_GZGJ.json失败",data:""}),ctx);
          return;
        }
        var poiName = `${DATA_PATH}Js_POI.json`;
        var poi;
        var poiObj = await readFile(poiName,2);
        if(Object.keys(poiObj).length == 0 || !poiObj['sites'] || !(poiObj['sites'] instanceof Array) || poiObj['sites'].length < 2){
          poi = [{},{ID:"GDJ0",Class:"Centre",Name:"BP_POI_GDJ0",Mesh:"SM_GDJ",X:"0",Y:"0",Z:"0",URL:"btgdj.html",Build:"1",Visible:"1",Click:"0",Init:"0",Color:"Green",R:"",G:"",B:""}];
        }else{
          poi = poiObj['sites'];
        }
        poi.splice(0,1,point);
        var ps = await writeFile(poiName,JSON.stringify({sites:poi}));
        if(ps){
          let obj = {type:res.data.type,origin:res.data.origin,finishing:res.data.finishing,finishingId:res.data.finishingId,distance:res.data.distance,X:res.data.x,Y:res.data.y,linkId:link.linkId,linkName:link.linkName,lineName:link.lineName,times:link.times,status:data.status,statusValue:data.statusValue,cancat:link.cancat,works:link.works};
          let rsFile = `${DATA_PATH}gaojing.json`;
          writeFile(rsFile,JSON.stringify(obj));
          setTimeout(async () => {
            json[0]['Click'] = "0";
            /* json[0]['R'] = "0";
            json[0]['G'] = "0";
            json[0]['B'] = "0"; */
            let tmp = await writeFile(fileName,JSON.stringify({sites:json}));
            poi[0]['Click'] = "0";
            /* poi[0]['R'] = "0";
            poi[0]['G'] = "0";
            poi[0]['B'] = "0"; */
            await writeFile(poiName,JSON.stringify({sites:poi}));
            updateJson(`${DATA_PATH}Js_UpData.json`);
          },500);//此处的数值代表点击模拟演习按钮时，把Js_POI.json中的Click变成1，过段时间后变成0，数值代表过多长时间后变成0，单位是毫秒，同时，会把Js_GZGJ.json中的Click也变成1，过段时间后变成了
          ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入JSON成功",data:""}),ctx);
          return;
        }else{
          ctx.app.emit("error",err.setDefaultValue({code:0,msg:"写入Js_POl失败",data:""}),ctx);
          return;
        }
      }else{
        ctx.app.emit("error",err.setDefaultValue({code:-1,msg:res.msg,data:res.data}),ctx);
        return;
      }
    }
  } catch (error) {
    console.log(error);
    ctx.app.emit("error",err.setDefaultValue({code:0,msg:"未知错误",data:obj.alarmType}),ctx);
      return;
  }
  
})
//暴露路由
module.exports = router;
